package com.pcbly.web.components.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.pcbly.web.Constants;

public class SecurityInterceptor extends AbstractInterceptor  {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3261060328146236922L;
	private Logger log = Logger.getLogger(this.getClass());
	public void destroy() {
		log.info("用户权限及安全性验证拦截器结束！");
		super.destroy();
	}

	public void init() {
		log.info("用户权限及安全性验证初始化！");
		super.init();
	}
	@Override
	public String intercept(ActionInvocation actionInvocation) throws Exception {
		// TODO Auto-generated method stub 
		//当前请求的action名称
		String actionName = actionInvocation.getInvocationContext().getName();
		HttpServletRequest request = ServletActionContext.getRequest();   
        HttpSession session = request.getSession();  
        //验证用户是否登录，只有在当前actionName不等于login时才判断session
        if(!actionName.equals("login")){ 
	        if(session.getAttribute(Constants.USER_SESSION_KEY) == null){
	        	log.info("用户尚未登录或登录已失效，请重新登录！");
	        	request.setAttribute("LOGINERROR", "用户尚未登录或登录已失效，请重新登录！"); 
	        	return "error";
	        }
        }
		return actionInvocation.invoke();
	}

}
